package br.edu.ufcg.dsc.actions.reservation;

import org.apache.struts2.config.ParentPackage;
import org.apache.struts2.config.Result;
import org.apache.struts2.dispatcher.ServletRedirectResult;

import br.edu.ufcg.dsc.actions.BaseLoggedAction;
import br.edu.ufcg.dsc.domain.Reservation;
import br.edu.ufcg.dsc.domain.Resource;
import br.edu.ufcg.dsc.domain.User;
import br.edu.ufcg.dsc.services.ReservationService;
import br.edu.ufcg.dsc.services.ResourceService;

import com.opensymphony.xwork2.ActionContext;

@Result(name = "success", type = ServletRedirectResult.class, value = "/index.action?message=Unit Reserved successfully")
@ParentPackage("myPackage")
public class ReservationUnitAction extends BaseLoggedAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private User user;
	private int  resourceId;
	
	public int getResourceId() {
		return resourceId;
	}

	public void setResourceId(int resourceId) {
		this.resourceId = resourceId;
	}

	@Override
	protected String executeIfLogged() throws Exception {
		Resource resource = ResourceService.find(resourceId);
		if (resource != null) {
			user = (User) ActionContext.getContext().getSession().get("user");
			Reservation reserve = new Reservation();
			reserve.setResource(resource);
			reserve.setUser(user);
			
			ReservationService.persist(reserve);
			
			return SUCCESS;
		}
		return ERROR;
	}
}
